import React, { useState, useEffect } from "react";  // 添加 useState, useEffect
import { useNavigate } from "react-router-dom";
import { Modal, Input } from 'antd';  // 添加这行
import { getApiUrl } from "../../config/api";
import SettingIcon from "../../assets/setting.svg";
import DefaultAvatar from "../../assets/avatar.png";  // 重命名为 DefaultAvatar
import { useGlobalContext } from "../../context/GlobalContext";
import "./index.css";

export const NavBottomArea = () => {
  const navigate = useNavigate();
  const { logout, user, updateUserInfo } = useGlobalContext();
  const [avatar, setAvatar] = useState(DefaultAvatar);
  const [isModalVisible, setIsModalVisible] = useState(false);  // 弹窗是否可见
  const [newValue, setNewValue] = useState('');  // 添加这行
  const [currentField, setCurrentField] = useState('');  // 添加这行
  console.log('当前用户', user);

  const handleSettingsClick = () => {
    navigate('/settings');
  };

  // 添加头像上传处理
  const handleAvatarChange = async (e) => {
    const file = e.target.files[0];
    if (!file) return;

    const formData = new FormData();
    formData.append('avatar', file);

    try {
      const token = localStorage.getItem('token');
      const response = await fetch(getApiUrl('/api/user/avatar'), {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${token.replace(/['"]+/g, '')}`
        },
        body: formData
      });

      const data = await response.json();
      if (data.ok) {
        setAvatar(data.avatarUrl);
      } else {
        throw new Error(data.error);
      }
    } catch (error) {
      console.error('上传头像失败:', error);
      alert('上传头像失败');
    }
  };

  // 添加头像加载
  useEffect(() => {
    const loadAvatar = async () => {
      if (user?.avatar) {
        setAvatar(user.avatar);
      }
    };
    loadAvatar();
  }, [user]);

  const handleProfileUpdate = async (field) => {
    setCurrentField(field);
    setNewValue('');
    setIsModalVisible(true);
  };

  const handleModalOk = async () => {
    if (!newValue) {
      alert('请输入新的值');
      return;
    }

    try {
      const token = localStorage.getItem('token');
      const response = await fetch(getApiUrl('/api/user/profile'), {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token.replace(/['"]+/g, '')}`
        },
        body: JSON.stringify({
          [currentField]: newValue
        })
      });

      const data = await response.json();
      if (data.ok) {
        const newUserData = { ...user, [currentField]: newValue };
        updateUserInfo(newUserData);
        setIsModalVisible(false);
        alert('修改成功！');
      } else {
        throw new Error(data.error);
      }
    } catch (error) {
      console.error('更新用户信息失败:', error);
      alert('更新失败');
    }
  };

  const handleCreationClick = () => {
    navigate('/creation');
  };

  return (
    <>
      <div className="nav-bottom">
        <div className="nav-bottom__item" onClick={handleSettingsClick}>
          <div className="nav-bottom__item-icon">
            <img src={SettingIcon} alt="设置" />
          </div>
          <div className="nav-bottom__item-name">设置</div>
        </div>

        {/* 添加 AI 创作按钮 */}
        <div className="nav-bottom__item" onClick={handleCreationClick}>
          <div className="nav-bottom__item-icon">
            <svg viewBox="0 0 24 24" width="16" height="16">
              <path
                fill="currentColor"
                d="M19 11h-4v4h-2v-4H9V9h4V5h2v4h4m1-7H4c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2z"
              />
            </svg>
          </div>
          <div className="nav-bottom__item-name">AI 创作</div>
        </div>

        <div className="nav-bottom__item">
          <label className="nav-bottom__item-icon" style={{ cursor: 'pointer' }}>
            <input
              type="file"
              accept="image/*"
              style={{ display: 'none' }}
              onChange={handleAvatarChange}
            />
            <img src={avatar} alt="头像" style={{ width: '24px', height: '24px', borderRadius: '50%' }} />
          </label>
          <div 
            className="nav-bottom__item-name" 
            onClick={() => handleProfileUpdate('nickname')}
            style={{ cursor: 'pointer' }}
          >
            {user?.nickname || 'User'}
          </div>
        </div>

        <div className="nav-bottom__item" onClick={logout}>
          <div className="nav-bottom__item-icon">
            <svg viewBox="0 0 24 24" width="16" height="16">
              <path
                fill="currentColor"
                d="M16 17v-3H9v-4h7V7l5 5-5 5M14 2a2 2 0 012 2v2h-2V4H5v16h9v-2h2v2a2 2 0 01-2 2H5a2 2 0 01-2-2V4a2 2 0 012-2h9z"
              />
            </svg>
          </div>
          <div className="nav-bottom__item-name">退出登录</div>
        </div>
      </div>

      <Modal
        title={`修改${currentField === 'nickname' ? '昵称' : '手机号'}`}
        open={isModalVisible}
        onOk={handleModalOk}
        onCancel={() => setIsModalVisible(false)}
        okText="确认"
        cancelText="取消"
      >
        <Input
          placeholder={`请输入新的${currentField === 'nickname' ? '昵称' : '手机号'}`}
          value={newValue}
          onChange={(e) => setNewValue(e.target.value)}
        />
      </Modal>
    </>
  );
};
